import json
import environ
import os
import sys
import django

ROOT_DIR = (
        environ.Path(__file__) - 3
)
sys.path.append(str(ROOT_DIR))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.local')
django.setup()

from apps.common.account.models import Role, Permission, RolePermissions
from apps.common.school.models import Faculty

# 获取所有二级单位
first_faculty_codes = Faculty.objects.filter(parent_code__isnull=True)\
    .exclude(faculty_title__in=('其它', '其他')) \
    .values_list('faculty_code', flat=True)
second_faculty_data = Faculty.objects \
    .filter(parent_code__in=first_faculty_codes) \
    .values('faculty_code', 'faculty_title')
second_faculty_dict = {i['faculty_code']: i['faculty_title'] for i in second_faculty_data}

# 创建角色
defaults = {'system_name': '获奖系统', 'name': "超级管理员", 'codename': 'admin',
            'desc': "超级管理员"}
role, _ = Role.objects.update_or_create(codename='admin', defaults=defaults)

tmp = {'system_name': '获奖系统', 'name': '二级学院权限', 'codename': 'second_faculty_perms', 'url': '', 'method': '',
       'sort_num': 10, 'level': 1}
father_permission, _ = Permission.objects.update_or_create(id=18, defaults=tmp)

tmp = {'system_name': '获奖系统', 'name': '查看所有二级学院', 'codename': 'view_all_second_faculty', 'url': '',
       'method': '', 'sort_num': 11, 'level': 2, 'parent_id': 18}
view_all_faculty_perm, _ = Permission.objects.update_or_create(id=19, defaults=tmp)

admin_role_perms_bulk_create = []
perm_qs = Permission.objects.all()
for i in perm_qs:
    admin_role_perms_bulk_create.append(RolePermissions(role=role, permission=i))
RolePermissions.objects.bulk_create(admin_role_perms_bulk_create, ignore_conflicts=True)

role_perms_bulk_create = []
pk = 30     # id从20开始
for i in second_faculty_data:
    # 所有二级单位
    # 创建角色
    defaults = {'system_name': '获奖系统', 'name': f"{i['faculty_title']}管理员", 'codename': i['faculty_code'],
                'desc': f"管理{i['faculty_title']}"}
    role, _ = Role.objects.update_or_create(codename=i['faculty_code'], defaults=defaults)
    # 创建权限
    tmp = {'system_name': '获奖系统', 'name': f"{i['faculty_title']}", 'codename': f"{i['faculty_code']}",
           'url': '', 'method': '', 'sort_num': pk, 'level': 2, 'parent_id': 18}
    perm, _ = Permission.objects.update_or_create(codename=i['faculty_code'], defaults=tmp)
    # 将权限分给角色
    role_perms_bulk_create.append(RolePermissions(role=role, permission=perm))

    # 为每个角色新增权限id为(2, 3, 6, 10, 11)的权限
    for perm_id in (2, 3, 6, 10, 11):
        role_perms_bulk_create.append(RolePermissions(role=role, permission_id=perm_id))

    # 页面权限
    page_perms = [RolePermissions(role=role, permission_id=i) for i in (1, 5, 9)]
    role_perms_bulk_create.extend(page_perms)
    pk += 1


# 去掉那些删除掉了的学院的权限
role_qs = Role.objects.all()
for i in role_qs:
    try:
        faculty_code = int(i.codename)
        if str(faculty_code) not in second_faculty_dict.keys():
            i.delete()
    except ValueError:
        continue
perm_qs = Permission.objects.all()
for i in perm_qs:
    try:
        faculty_code = int(i.codename)
        if str(faculty_code) not in second_faculty_dict.keys():
            i.delete()
    except ValueError:
        continue

RolePermissions.objects.bulk_create(role_perms_bulk_create, ignore_conflicts=True)

print('初始化成功')